import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_delete_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_folder_detail_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_banner_image_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_package_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_single_upload_edit_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_set_image_cover_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_common_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_type_list_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_media_play_module_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_water_list_page.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../smart_home_upload_service.dart';

/// 智能家居更多操作
class SmartHomeFolderImageDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeFolderImageDetailPage";
  //品牌或门店信息
  final String title;
  final String shid;
  final SmartHomeFolderDetailDataBean folderData;
  final List<ColumnListBean> columnList;
  //列表中选中的scid
  final String parentScid;

  const SmartHomeFolderImageDetailPage(
      {Key key,
        this.shid,
        this.parentScid,
        this.title,
        this.folderData,
        this.columnList,
      }) : super(key:key);

  @override
  _SmartHomeFolderImageDetailPageState createState() => _SmartHomeFolderImageDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context,
      String shid, String parentScid, String title, SmartHomeFolderDetailDataBean folderData,
      List<ColumnListBean> columnList,
      ){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeFolderImageDetailPage(
          shid: shid,
          parentScid: parentScid,
          title: title,
          folderData: folderData,
          columnList: columnList,
        ),
        routeName: SmartHomeFolderImageDetailPage.ROUTER
    );
  }
}

class _SmartHomeFolderImageDetailPageState
    extends BaseState<SmartHomeFolderImageDetailPage> {
  SmartHomeStoreDetailCommonViewModel _viewModel;
  SmartHomeFolderDetailDataBean _folderData;
  FolderInfoBean _folderInfo;
  StreamSubscription _detailUpdateStreamSubscription;
  List<FolderPicListBean> _folderPicList;
  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeStoreDetailCommonViewModel(this);
    _folderData = widget?.folderData;
    _folderInfo = _folderData?.folderInfo;
    _folderPicList = _folderData?.folderPicList;
    _getLatestData();
    _detailUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeFolderDetailEvent>()?.listen((event) {
          _getLatestData();
        });
  }

  void _getLatestData(){
    _viewModel.getFolderDetailWithValueNotifier(widget?.shid??"", _folderInfo?.sfid??"",  _folderInfo?.getFlg()??"", "", (folderDetailData){
      _folderData = folderDetailData;
      _folderPicList = _folderData?.folderPicList;
      _folderInfo = _folderData?.folderInfo;
      setState(() {});
    });
  }


  @override
  void dispose() {
    _detailUpdateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toScrollWidget(),



      ],
    );
  }


  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toMoreOperationsWidget(),
      rightPadding: 0,
    );
  }

  ///更多操作
  Widget _toMoreOperationsWidget(){
    return Visibility(
      visible: !(_folderInfo?.isSysPush()??false),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          _more();
        },
        child: Container(
          height: 44,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Image.asset(
            "images/icon_more_horizontal.png",
            width: 20,
            height: 20,
          ),
        ),
      ),
    );
  }

  ///更多
  _more() {
    Map<String, VoidCallback> map = {
      "编辑": () async {
        ColumnListBean currentColumn = null;
        widget?.columnList?.forEach((element) {
          if (element?.scid == _folderInfo?.scid) {
            currentColumn = element;
          }
        });
        List<SmartHomeUploadItemBean> currentList = new List();
        //图片
        int coverIndex = 0;
        _folderPicList.forEach((element) {
          currentList.add(SmartHomeUploadItemBean(
            netUrl: element.picurl,
            type: "01",
            scid: element.scid??"",
            scidName: element.scname??"",
            folderWidth: int.parse(element?.picsize?.split("*")[0]),
            folderHeight: int.parse(element?.picsize?.split("*")[1]),
            picstorage: element?.picstorage??"",
            stid: element.stid??"",
            stidName: element.stname??"",
            style: element?.style??"99",
            backup: element.backup??"",
            picid: element?.picid??"",
            styleName: element?.stylename??"",
          ));
          if(element.picurl == _folderInfo.coverurl){
            coverIndex = _folderPicList.indexOf(element);
          }
        });

        MusicListBean musicInfo;
        if(StringUtils.isNotEmpty(_folderInfo?.id)){
          musicInfo = new MusicListBean();
          musicInfo.murl = _folderInfo?.murl;
          musicInfo.author = _folderInfo?.author;
          musicInfo.mname = _folderInfo?.mname;
          musicInfo.msize = _folderInfo?.msize;
          musicInfo.id = _folderInfo?.id;
          musicInfo.mtime = _folderInfo?.mtime;
        }
        if(currentList.length == 1){
          SmartHomePublishImageSingleUploadEditPage.navigatorPush(context,
              widget?.shid,
              currentList,
              sfid: _folderInfo.sfid,
            router: SmartHomeFolderImageDetailPage.ROUTER,);
        }else{
          SmartHomePublishImagePackageUploadPage.navigatorPush(
              context,
              widget?.shid,
              currentList: currentList,
              sfid: _folderInfo.sfid,
              title: _folderInfo.title,
              desc: _folderInfo.backup,
              coverIndex: coverIndex,
              router: SmartHomeFolderImageDetailPage.ROUTER,
              musicInfo: musicInfo,
              isCreate: false
          );
          // SmartHomePublishPage.navigatorPush(
          //     context,
          //     widget?.shid,
          //     "01",
          //     widget?.columnList,
          //     currentColumn,
          //     currentList: currentList, sfid: _folderInfo.sfid,
          //     title: _folderInfo.title,
          //     desc: _folderInfo.backup,
          //     coverIndex: coverIndex,
          //     router: SmartHomeFolderImageDetailPage.ROUTER,
          //     musicInfo: musicInfo,
          //     isCreate: false
          // );
        }
      },
      "删除": () async {
        bool result = await CommonDeleteCancelDialog.navigatorPushDialog(context);
        if (result ?? false) {
          _viewModel.deleteFolder(
              context,  widget?.shid, _folderInfo?.scid??"",
              _folderInfo?.sfid, _folderPicList.elementAt(0).videoid,
              parentScid: widget?.parentScid??""
          );
        }
      }
    };

    CommonMoreMenuDialog.navigatorPushDialog(
      context,
      map,
      bgColor: Colors.white,
      splitColor: Color(0xFFF6F7F9),
      textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      lineColor: Color(0xFFEEEEEE),
    );
  }

  Widget _toScrollWidget(){
    return Expanded(
      child: ListView(
        padding: EdgeInsets.all(0),
        children: [
          _toInfoWidget(),
          _toDesWidget(),
          SizedBox(height: 8.5,),
          _toGridWidget(),
        ],
      ),
    );
  }

  ///动态信息
  Widget _toInfoWidget(){
    int picWidth = int.parse((_folderInfo?.coversize??"1*1").split("*")[0]??1);
    int picHeight = int.parse((_folderInfo?.coversize??"1*1").split("*")[1]??1);
    double scale = picHeight/picWidth;
    double imgHeight = 80;
    double imgWidth = 60;
    if(scale >= 4/3){
      imgHeight = 80;
      imgWidth = 60;
    }else{
      imgHeight = 80;
      imgWidth = 80;
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 15),
      color: Color(0xFFF6F7F9),
      alignment: Alignment.topLeft,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _folderInfo?.getTitle()??"",
                  style: TextStyle(
                    fontSize: 17,
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),

                SizedBox(height: 8,),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Center(
                      child: Container(
                        height: 20,
                        padding: EdgeInsets.symmetric(horizontal: 8),
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Color(0XFFCFD4DB),
                        ),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: 250,
                          ),
                          child: Text(
                            widget?.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 12,
                              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8,),
                Text(
                  _folderInfo?.getPublishInfo()??"",
                  style: TextStyle(
                    fontSize: 10,
                    color: Color(0XFF8B93A5),
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          SizedBox(width: 15,),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: ()async{
              if("-1" == _folderInfo.shid){
                return;
              }
              if(_folderPicList.length == 1){
                SmartHomeFolderBannerImagePage.navigatorPush(context, _folderInfo?.scid, "01", widget?.title, _folderData, widget?.columnList);
              }else{
                List<SmartHomeUploadItemBean> currentList = new List();
                int coverIndex = 0;
                _folderPicList.forEach((element) {
                  currentList.add(SmartHomeUploadItemBean(
                    netUrl: element.picurl,
                    type: "01",
                    scid: element.scid??"",
                    shid: _folderInfo.shid??"",
                    sfid: _folderInfo.sfid??"",
                    folderWidth: int.parse(element?.picsize?.split("*")[0]),
                    folderHeight: int.parse(element?.picsize?.split("*")[1]),
                    picstorage: element?.picstorage??"",
                    stid: element.scid??"",
                    style: element?.style??"99",
                    backup: element.backup??"",
                  ));
                  if(element.picurl == _folderInfo.coverurl){
                    coverIndex = _folderPicList.indexOf(element);
                  }
                });
                SmartHomePublishSetImageCoverPage.navigatorPush(
                    context, currentList, coverIndex, editCover: true);
              }
            },
            child: Container(
              margin: EdgeInsets.only(top: 2),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: VgCacheNetWorkImage(
                  _folderInfo?.coverurl ?? "",
                  width:imgWidth,
                  height: imgHeight,
                  imageQualityType: ImageQualityType.middle,
                ),
              ),
            ),
          )

        ],
      ),
    );
  }

  ///描述
  Widget _toDesWidget(){
    if(StringUtils.isNotEmpty(_folderInfo?.backup??"")){
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 15),
        margin: EdgeInsets.only(top: 12.5),
        child: Text(
          _folderInfo?.backup??"",
          style: TextStyle(
              fontSize: 15,
              color: ThemeRepository.getInstance().getCardBgColor_21263C()
          ),
        ),
      );
    }
    return SizedBox(height: 4,);

  }

  ///图片布局
  Widget _toGridWidget(){
    return ScrollConfiguration(
        behavior: MyBehavior(),
        child: GridView.builder(
          padding: EdgeInsets.only(
              top: 0,
              left: 15,
              right: 15,
              bottom: getNavHeightDistance(context)),
          itemCount: _folderPicList?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 4,
            crossAxisSpacing: 5,
            childAspectRatio: 112 / 128,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context, index);
          },
        ));
  }

  Widget _toGridItemWidget(BuildContext context, int index) {
    FolderPicListBean itemBean = _folderPicList?.elementAt(index);
    double width = (ScreenUtils.screenW(context) - 30 -10)/3;
    double containerHeight = (width * 128)/112;
    print("containerHeight:" + containerHeight.toString());
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        // _onTap(itemBean);
        SmartHomeFolderBannerImagePage.navigatorPush(context, _folderInfo?.scid,
            "01", widget?.title, _folderData, widget?.columnList,
            selectIndex: index);
      },
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: VgCacheNetWorkImage(
              itemBean?.getCoverUrl() ?? "",
              width:width,
              height: width,
              imageQualityType: ImageQualityType.middle,
            ),
          ),
          SizedBox(height: 2,),
          Container(
            height: (containerHeight - width -2),
            width: width,
            child: Text(
              itemBean?.getLabel()??"",
              style: TextStyle(
                fontSize: 10,
                color: Color(0XFF8B93A5),
              ),
            ),
          ),
        ],
      ),
    );
  }


}
